package com.lychee.moli.controller;

import com.lychee.moli.entity.BaseResultEntity;
import com.lychee.moli.entity.IdentityEntity;
import com.lychee.moli.entity.StoreEntity;
import com.lychee.moli.outher.IConstant;
import com.lychee.moli.service.IStoreService;
import com.lychee.moli.utils.TextUtils;
import com.lychee.moli.utils.TokenUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Lychee on 2018/4/12 09:48.
 * <p>
 * Author:Hejingzhou
 * <p>
 * Email:tcowork@163.com
 */
@Controller
@RequestMapping(value = "/Store")
public class StoreController {

    @Resource
    private IStoreService storeService;

    private Logger logger = Logger.getLogger(StoreController.class);

    /**
     * 创建店铺
     *
     * @param storeName  店铺名称
     * @param storePhone 店铺手机号
     * @param request    request
     * @return 一定别TM忘了添加@ResponseBody  才能返回正常的Json
     */
    @RequestMapping(value = "/createStore")
    @ResponseBody
    public BaseResultEntity<String> createStore(@RequestParam(value = "storeName") String storeName,
                                                @RequestParam(value = "storePhone") String storePhone,
                                                @RequestParam(value = "storeCover", required = false) List<MultipartFile> multipartFiles,
                                                HttpServletRequest request) {

        try {
            List<String> mStoreCoverList = new ArrayList<String>();
            if (multipartFiles != null) {
                for (MultipartFile file : multipartFiles) {
                    if (!file.isEmpty()) {
                        logger.info("上传文件的名称" + file.getOriginalFilename()
                                + "\t大小" + (file.getSize() / 1024F)
                                + "K\t内容类型" + file.getContentType());

                        String path = "/Users/hejingzhou/Desktop/ImageRepositories";
                        String fileName = file.getOriginalFilename();
                        File filePath = new File(path, fileName);

                        if (!filePath.getParentFile().exists()) {
                            boolean mkdirs = filePath.getParentFile().mkdirs();
                            if (!mkdirs) {
                                return new BaseResultEntity<String>(BaseResultEntity.ERROR_CODE_FAIL, "错误", "创建错误");
                            }
                        }
                        file.transferTo(new File(path + File.separator + fileName));
                        mStoreCoverList.add(path + File.separator + fileName);
                    }
                }
                for (String s : mStoreCoverList) {
                    logger.info("存入硬盘路径\t" + s);
                }
            }

            if (!TextUtils.isEmpty(storeName) && !TextUtils.isEmpty(storePhone)) {
                IdentityEntity identityEntity = TokenUtils.parseTokenMessage(request.getHeader(IConstant.TOKEN), TokenUtils.SECRET_KEY);
                if (identityEntity.getUserId() == null) {
                    // TODO: 2018/4/12 需要用户登录
                } else {
                    int createOk = 0;
                    try {
                        StoreEntity storeEntity = new StoreEntity();
                        storeEntity.setStoreName(storeName);
                        storeEntity.setStorePhone(storePhone);

                        createOk = storeService.createStore(storeEntity);

                        int storeID = storeEntity.getStoreID();
                        logger.info("返回的主键ID\t" + storeID);

                        for (String s : mStoreCoverList) {
                            storeService.saveStoreImage(String.valueOf(storeID), s);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    logger.info("影响条数：" + createOk);
                    if (createOk > 0) {
                        logger.info("创建成功");
                        return new BaseResultEntity<String>(BaseResultEntity.ERROR_CODE_SUCCESS, "创建成功", "创建成功");
                    } else {
                        logger.error("创建失败");
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new BaseResultEntity<String>(BaseResultEntity.ERROR_CODE_FAIL, "错误", "创建错误");
    }


    @RequestMapping(value = "/storeDetail")
    public BaseResultEntity<StoreEntity> storeDetail(@RequestParam("storeId") String storeId, HttpServletRequest request) {

        if (!TextUtils.isEmpty(storeId)) {
            StoreEntity storeEntity = storeService.queryStoreDetail(storeId);
            if (storeEntity != null) {
                logger.info(storeEntity.toString());
                return new BaseResultEntity<StoreEntity>(BaseResultEntity.ERROR_CODE_SUCCESS, storeEntity, "请求成功");
            }
        }
        return new BaseResultEntity<StoreEntity>(BaseResultEntity.ERROR_CODE_SUCCESS, null, "请求成功");
    }
}
